<template>
	<view>
		<unicloud-db ref="udb" collection="carList" v-slot:default="{ loading, data }" @load="load">
			<view class="list-item" v-for="(v, i) in data" :key="i">
				<label>
					<checkbox :checked="v.state" @click="switchState(v)" />
				</label>
				<view class="left">
					<image :src="v.image" mode=""></image>
				</view>
				<view class="right">
					<view class="title">{{ v.title }}</view>
					<view class="desc">{{v.desc}}</view>
					<view class="count">
						<button size="mini" @click="sub(v)">-</button>
						<text>{{ v.count }}</text>
						<button size="mini" @click="add(v)">+</button>
					</view>
					<view class="price">¥：{{ v.price }}</view>
				</view>
			</view>
		</unicloud-db>

		<view class="">
			总价： {{totalPrice}}

			<label>
				<checkbox :checked="totalState" @click="changeAllState(!totalState)" /><text>全选</text>
			</label>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				data: []
			};
		},
		computed: {
			totalPrice() {
				return this.data.reduce((p, n) => {
					return n.state ? p + n.price * n.count : p
				}, 0)
			},
			totalState() {
				return this.data.every(v => v.state)
			}
		},
		methods: {
			load(data) {
				this.data = data
			},
			async add(item) {
				const resp = await uniCloud.callFunction({
					name: 'add_to_car_list',
					data: {
						item: item
					}
				})
				uni.showToast({
					title: resp.result.message
				});
				// this.$refs.udb.refresh()
				item.count++
			},
			async sub(item) {
				const resp = await uniCloud.callFunction({
					name: 'sub_to_car_list',
					data: {
						item: item
					}
				})
				uni.showToast({
					title: resp.result.message
				})
				// this.$refs.udb.refresh()
				item.count--
			},
			async switchState(item) {
				const resp = await uniCloud.callFunction({
					name: 'switch_state_car_list',
					data: {
						item: item
					}
				})
				// this.$refs.udb.refresh()
				item.state = !item.state
			},
			async changeAllState(state) {
				this.data.forEach(v => v.state = state);
				await uniCloud.callFunction({
					name: 'switch_all_state_car_list',
					data: {
						state: state
					}

				})

			}
		}
	}
</script>

<style lang="scss" lang="scss">
	.list-item {
		display: flex;

		.left {
			width: 300rpx;
			height: 240rpx;
			flex-shrink: 0;

			image {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>